import time
import board
import adafruit_dht
import logging
from config.config import DHT22_PIN

logger = logging.getLogger(__name__)

class DHT22Sensor:
    def __init__(self):
        logger.info(f"初始化DHT22传感器，使用GPIO{DHT22_PIN}")
        self.sensor = adafruit_dht.DHT22(getattr(board, f'D{DHT22_PIN}'))

    def read(self):
        """读取温湿度数据"""
        try:
            temperature = self.sensor.temperature
            humidity = self.sensor.humidity
            logger.debug(f"DHT22读取数据：温度={temperature}°C, 湿度={humidity}%")
            return temperature, humidity
        except RuntimeError as e:
            logger.warning(f"DHT22读取失败: {str(e)}")
            return None, None
        
    def read_average(self, times=5, interval=2):
        """多次读取取平均值"""
        logger.info(f"开始DHT22多次读取，次数={times}，间隔={interval}秒")
        temps = []
        hums = []
        
        for i in range(times):
            temp, hum = self.read()
            if temp is not None and hum is not None:
                temps.append(temp)
                hums.append(hum)
            time.sleep(interval)
        
        if not temps or not hums:
            logger.error("DHT22多次读取全部失败")
            return None, None
            
        avg_temp = sum(temps)/len(temps)
        avg_hum = sum(hums)/len(hums)
        logger.info(f"DHT22平均值：温度={avg_temp:.1f}°C, 湿度={avg_hum:.1f}%")
        return avg_temp, avg_hum

    def cleanup(self):
        """清理资源"""
        logger.info("清理DHT22传感器资源")
        self.sensor.exit()